package com.app.utils.util.file;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.app.utils.util.ToastUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 文件操作类
 *
 * @author xuxinghai
 */
public class AppFileUtils {

    /**
     * 得到文件的大小
     *
     * @param file
     * @return 大小单位 byte
     */
    public static long getFolderSize(File file) {
        if (!file.exists())
            return 0;
        long size = 0;
        File[] fileList = file.listFiles();
        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isDirectory()) {
                size = size + getFolderSize(fileList[i]);
            } else {
                size = size + fileList[i].length();
            }
        }
        return size;
    }

    /**
     * 删除某文件夹下的文件
     *
     * @param file
     */
    public static void clearCache(File file) {
//        LogUtils.e("gzq","file="+file.getAbsolutePath());
        if (!file.exists()){
//            LogUtils.e("gzq","bucunzai---file="+file.getAbsolutePath());
            return;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                if (f.isDirectory())
                    clearCache(f);
                else
                    f.delete();
            }
        } else
            file.delete();
    }

    /**
     * 安装文件
     *
     * @param file
     * @param context
     */
    public static void installFile(File file, Context context) {
        if (file == null) {
            ToastUtils.makeText("下载失败,请重新下载");
            return;
        }
        if (!file.exists()) {
            ToastUtils.makeText("找不到文件,请重新下载");
            file.delete();
            return;
        }

        try {
//			Uri playUri1 = Uri.parse("file:///" + Config.APKFLODER
//					+ Config.SPREARATOR + file.getName());
//			Intent it = new Intent(Intent.ACTION_VIEW, playUri1);
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            it.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
            context.startActivity(it);

            //安装成功后 关闭推荐下载应用对应通知栏 暂设不消失
//			NotificationManager manager = (NotificationManager) AppApplication.getApp().getSystemService(Context.NOTIFICATION_SERVICE);
//			manager.cancel(NotifyUtils.checkBoxUpdate);

        } catch (Exception e) {
            ToastUtils.makeText("安装错误");
            file.delete();
        }
    }

    /**
     * 得到sd是否正常挂载
     *
     * @return
     */
    public static boolean getSDState() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }


//    /**
//     * 安装弹窗
//     *
//     * @param mContext
//     * @param name
//     * @param file
//     */
//    public static void installAppDiaLog(final Context mContext, final String name, final File file) {
//        CustomDialog.Builder alertDialog = new CustomDialog.Builder(mContext);
//        Resources mResourse = mContext.getResources();
//        alertDialog.setTitle("下载完成");
//        alertDialog.setMessage("最新版应用 " + name + "\n已经下载完成!是否安装?");
//        alertDialog.setPositiveButton(
//                mResourse.getString(R.string.common_cancel),
//                new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog,
//                                        int which) {
//                        dialog.dismiss();
//                        dialog.cancel();
//                    }
//
//                });
//        alertDialog.setNegativeButton(
//
//
//                mResourse.getString(R.string.common_confirm),
//                new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog,
//                                        int which) {
//                        dialog.dismiss();
//                        installFile(file, mContext);// 安装文件
//                    }
//
//                });
//
//        alertDialog.create().show();
//    }


    /**
     * 新建文件,以时间戳命名
     *
     * @param path 父目录文件路径
     * @return
     */
    public static File getImageFile(String path) throws Exception {
        File imageFile = new File(path, System.currentTimeMillis() + ".jpg");
        if (!imageFile.exists()) {
            imageFile.createNewFile();
        }
        return imageFile;
    }


    /**
     * 得到路径文件夹
     * 没有文件夹则新建
     *
     * @return
     */
    public static File getPathFile(String path) {
        File file = new File(path);
        if (file != null && !file.exists()) {
            file.mkdirs();
        }
        return file;
    }





    /**
     * 通过网址得到对应的文件
     *
     * @param url
     * @return
     */
    public synchronized static File getFileByUrl(String url, String path) {
        File offFile = getPathFile(path);
        if (offFile == null || !offFile.exists())
            return null;
        String s = "";
        s = url.replaceAll("[^(a-zA-Z0-9)]", "");
        File file = new File(offFile.getAbsolutePath() + File.separator + s);
        if (!file.exists())
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return file;
    }

    /**
     * 将字符串写入指定文件
     *
     * @param res 原字符串
     *            文件路径
     * @return 成功标记
     */
    public synchronized static boolean string2File(String res, File file) {
        boolean flag = false;
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            bufferedReader = new BufferedReader(new StringReader(res));
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            char buf[] = new char[4096]; // 字符缓冲区
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
                bufferedWriter.flush();
            }
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 文本文件转换为指定编码的字符串
     *
     * @param file     文本文件
     * @param encoding 编码类型
     * @return 转换后的字符串
     * @throws IOException
     */
    public static String file2String(File file, String encoding) {
        InputStreamReader reader = null;
        StringWriter writer = new StringWriter();
        try {
            if (encoding != null && !"".equals(encoding)) {
                reader = new InputStreamReader(new FileInputStream(file),
                        encoding);
            } else {
                reader = new InputStreamReader(new FileInputStream(file));
            }
            // 将输入流写入输出流
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (Exception e) {

            e.printStackTrace();
            return null;
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        // 返回转换结果
        if (writer != null)
            return writer.toString();
        else
            return null;
    }




    public static String ReadFile (File file){
        FileInputStream fis = null;
        StringBuilder sb = new StringBuilder();
        try{
           fis = new FileInputStream(file);
            // 设定读取的字节数
            int n = 512;
            byte buffer[] = new byte[n];
            // 读取输入流
            while ((fis.read(buffer, 0, n) != -1) && (n > 0)) {

                sb.append(new String(buffer));
            }
            // 关闭输入流
            fis.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        String s = sb.toString();

        return sb.toString();

    }


    /**
     * 写入debug文件
     *
     * @param url
     * @param className
     * @param content
     */
    public static void writeDebugFile(final String url, final String className,
                                      final String content,String filepath) {
        final String sdpath = filepath;
        new Thread() {
            public void run() {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                        "yyyy-MM-dd-hh-mm-ss");
                String time = simpleDateFormat.format(new Date(System
                        .currentTimeMillis()));
                String str = "\n\r ----  \n\r ---- \n\r ---- \n\r ---- debug: \n\r ---- url="
                        + url
                        + " \n\r ---- className="
                        + className
                        + "\n\r ---- time="
                        + time
                        + " \n\r ---- content="
                        + content;
                File file = new File(sdpath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File file2 = new File(file.getAbsolutePath() + File.separator
                        + "app_debug1");
                if (!file2.exists()) {
                    try {
                        file2.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                FileWriter fileWriter = null;
                PrintWriter printWriter = null;
                try {
                    fileWriter = new FileWriter(file2, true);
                    printWriter = new PrintWriter(fileWriter);
                    printWriter.flush();
                    printWriter.print(str);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (fileWriter != null) {
                        try {
                            fileWriter.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (printWriter != null) {
                        printWriter.close();
                    }
                }
            }

            ;
        }.start();
    }

    /**
     * 将数据写入文件中
     *
     * @param url
     * @param data
     * @param path
     */
    public static void saveData(final String url, final String data, final String path) {
        if (TextUtils.isEmpty(data)) {
            return;
        }
        new Thread() {
            @Override
            public void run() {
                File file = AppFileUtils.getFileByUrl(url, path);
                AppFileUtils.string2File(data, file);
            }
        }.start();
    }


    /**
     * 读取文件中的数据
     *
     * @param url
     * @param path
     * @param encoding
     * @return String
     */
    public static String readData(final String url, final String path, final String encoding) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        File file = AppFileUtils.getFileByUrl(url, path);
        String fileString = AppFileUtils.file2String(file, encoding);
        return fileString;
    }


    /**
     * 删除图片文件
     * @param context
     * @param file
     */
    public  static void deleteImageFile(Context context,File file){

        if(file!=null && file.exists()){
            context.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?",new String[]{file.getAbsolutePath()});
            boolean delete = file.delete();
        }
    }


    public static final String POSTFIX = ".JPEG";
    public static final String DEFAULT_NAME = "Photograph";
    /**
     * 创建一个.jpeg结尾的文件,文件精确到毫秒
     * @param context
     * @param parentPath
     * @return
     */
    public  static File createMediaFile(Context context,String parentPath){
        String state = Environment.getExternalStorageState();
        File rootDir = state.equals(Environment.MEDIA_MOUNTED)?Environment.getExternalStorageDirectory():context.getCacheDir();

        File folderDir = new File(rootDir.getAbsolutePath() + parentPath);
        if (!folderDir.exists()){
            folderDir.mkdirs();
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.CHINA).format(new Date());
        String packageName = context.getPackageName();

        String temp = "";
        if(!TextUtils.isEmpty(packageName)){
            String[] split = packageName.split("\\.");
            String packageNameEnd = split[split.length - 1];
            if(!TextUtils.isEmpty(packageNameEnd)){
                temp = packageNameEnd;
            }
        }else{
            temp = DEFAULT_NAME;
        }

        String fileName = temp + "_" + timeStamp + "";
        File tmpFile = new File(folderDir, fileName + POSTFIX);
        return tmpFile;
    }


}
